package com.yohann.algorithm;

import java.util.Arrays;

/**
 * <p>
 * 归并排序
 * </p>
 *
 * @author Yohann
 * @since 2020/12/29 20:28
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];

        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 归并排序
     *
     * @param arr   待排序数组
     * @param left  左边索引
     * @param right 右边索引
     * @param temp  中转临时数组
     */
    private static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int middle = (left + right) / 2;
            //向左递归进行分解
            mergeSort(arr, left, middle, temp);

            //向右递归进行分解
            mergeSort(arr, middle + 1, right, temp);

            //合并
            merge(arr, middle, left, right, temp);
        }
    }

    /**
     * 归并排序
     *
     * @param arr    待排序数组
     * @param middle 中间索引
     * @param left   左边索引
     * @param right  右边索引
     * @param temp   中转临时数组
     */
    private static void merge(int[] arr, int middle, int left, int right, int[] temp) {
        System.out.println("left=" + left + "    right=" + right);
        //初始化索引
        int i = left, j = middle + 1, t = 0;

        //先把左右两边（有序）的数据拷贝到temp数组
        while (i <= middle && j <= right) {
            //索引后移
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                t++;
                i++;
            } else {
                temp[t] = arr[j];
                t++;
                j++;
            }
        }

        //左边有剩
        while (i <= middle) {
            temp[t] = arr[i];
            t++;
            i++;
        }

        //右边有剩
        while (j <= right) {
            temp[t] = arr[j];
            t++;
            j++;
        }

        //将临时数组合并到原数组
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[t];
            t++;
            tempLeft++;
        }
    }
}